package com.hxzon.aixzsecretary.net;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.hxzon.aixzsecretary.xml.AixzMessageProcessor;

public class UserDialog {
	private Socket socket;
	private String messagetype;
	private ObjectInputStream dis;
	// private AixzMessageProcessor xml;

	private JFrame frame;
	private JPanel cPane;
	private JTabbedPane tabbedPane;

	private String username;
	private String IP;
	private static String myname;
	private static String myIP;
	private Date time;// send or receive time
	// chat data
	private String chatContent;
	// message data
	private String messageSubject;
	private String messageContent;
	private Date messageTime;
	// file data
	private String filename;
	private String filelength;
	private float filelength1;
	private String filepath;

	static {
		myname = System.getProperty("user.name");
		try {
			myIP = InetAddress.getLocalHost().getHostAddress();
			System.out.println(myIP);
		} catch (UnknownHostException e) {
		}
	}

	public UserDialog(String username, String IP) {
		this.username = username;
		this.IP = IP;
		messagetype = " ";
		showface();
	}

	public UserDialog(Socket socket, String messagetype) {
		this.socket = socket;
		this.messagetype = messagetype;
		readData();
		showface();
	}

	private void readData() {
		readUserData();
		if (messagetype.equals("chat"))
			readChatData();
		else if (messagetype.equals("message"))
			readMessageData();
		else if (messagetype.equals("file"))
			readFileData();
	}

	private void readUserData() {
		try {
			dis = new ObjectInputStream(new BufferedInputStream(socket
					.getInputStream()));
			username = dis.readUTF();
			IP = dis.readUTF();
			time = (Date) dis.readObject();
		} catch (Exception e) {
			System.out.println("readUserData wrong");
		}
	}

	private void readChatData() {
		try {
			chatContent = username + "  " + IP + "  " + time + "\n    "
					+ dis.readUTF();
			dis.close();
		} catch (Exception e) {
			System.out.println("readChatData wrong");
		}
	}

	private void readMessageData() {
		try {
			messageSubject = dis.readUTF();
			messageContent = dis.readUTF();
			messageTime = (Date) dis.readObject();// Date
			dis.close();
		} catch (Exception e) {
			System.out.println("readMessageData wrong");
		}
	}

	private void readFileData() {
		try {
			filelength1 = dis.readFloat();
			System.out.println(filelength1);
			filename = dis.readUTF();
			System.out.println(filename);
			filelength = dis.readUTF();
			System.out.println(filelength);
		} catch (Exception e) {
			System.out.println("readFileData wrong");
		}
	}

	public void showface() {
		frame = new JFrame(username + " : " + IP);
		frame.setBounds(100, 100, 250, 300);
		cPane = (JPanel) frame.getContentPane();
		cPane.setLayout(new BoxLayout(cPane, BoxLayout.Y_AXIS));

		tabbedPane = new JTabbedPane();
		cPane.add(tabbedPane);
		// tabItem
		JPanel messageTabItem = new JPanel();
		tabbedPane.add("message", messageTabItem);

		JPanel chatTabItem = new JPanel();
		tabbedPane.add("chat", chatTabItem);

		JPanel sendfileTabItem = new JPanel();
		tabbedPane.add("sendfile", sendfileTabItem);

		JPanel savefileTabItem = new JPanel();
		tabbedPane.add("savefile", savefileTabItem);
		tabbedPane.setEnabledAt(3, false);

		// sendfile pane
		sendfileTabItem.setLayout(new BorderLayout());
		final JTextArea filepathArea = new JTextArea();
		filepathArea.setLineWrap(true);
		filepathArea.setBackground(Color.white);
		sendfileTabItem.add(new JScrollPane(filepathArea), BorderLayout.CENTER);

		JPanel fileButtonPane = new JPanel();
		sendfileTabItem.add(fileButtonPane, BorderLayout.EAST);
		fileButtonPane
				.setLayout(new BoxLayout(fileButtonPane, BoxLayout.Y_AXIS));

		JButton filepathButton = new JButton("浏览        ");
		filepathButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();// 选择附件
				fileChooser.showOpenDialog(null);
				if (fileChooser.getSelectedFile() != null) {
					filepath = fileChooser.getSelectedFile().getAbsolutePath();
					filepathArea.setText(filepath);
				}
			}
		});
		fileButtonPane.add(filepathButton);

		JButton sendButton = new JButton("发送文件");
		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new FileClient(IP, myname, myIP, filepath).start();
				System.out.println("send file");
			}
		});
		fileButtonPane.add(sendButton);
		// savefile pane
		if (messagetype.equals("file")) {
			tabbedPane.setSelectedIndex(3);
			tabbedPane.setEnabledAt(3, true);
		}
		savefileTabItem.setLayout(new BorderLayout());
		final JTextArea fileInfoArea = new JTextArea(filename + "   "
				+ filelength);
		fileInfoArea.setLineWrap(true);
		fileInfoArea.setEditable(false);
		savefileTabItem.add(new JScrollPane(fileInfoArea), BorderLayout.CENTER);

		JPanel savefileButtonPane = new JPanel();
		savefileTabItem.add(savefileButtonPane, BorderLayout.EAST);
		savefileButtonPane.setLayout(new BoxLayout(savefileButtonPane,
				BoxLayout.Y_AXIS));

		final JButton savefileButton = new JButton("接收文件");
		savefileButtonPane.add(savefileButton);

		final JButton rejectfileButton = new JButton("拒绝        ");
		savefileButtonPane.add(rejectfileButton);

		savefileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				File file = new File(filename);
				fileChooser.setSelectedFile(file);
				// fileChooser.setCurrentDirectory(null);?
				if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION
						&& fileChooser.getSelectedFile() != null) {
					filepath = fileChooser.getSelectedFile().getAbsolutePath();
					try {
						DataOutputStream fos = new DataOutputStream(
								new BufferedOutputStream(new FileOutputStream(
										filepath)));
						int bufferSize = 81920;
						byte[] buf = new byte[bufferSize];
						DataOutputStream dos = new DataOutputStream(
								new BufferedOutputStream(socket
										.getOutputStream()));
						dos.writeUTF("yes");
						dos.flush();
						int process = 0;
						while (true) {
							int read = 0;
							if (dis != null)
								read = dis.read(buf);
							if (read == -1)
								break;
							fos.write(buf, 0, read);
							fos.flush();
							process += read;
							int precesent = (process)
									/ ((int) filelength1 / 100);
							fileInfoArea.append("\n已经完成总进度的" + precesent + "%");
						}
						fileInfoArea.append("\n文件传送完毕");
						dos.close();
						dis.close();
						fos.close();
						savefileButton.setEnabled(false);
						rejectfileButton.setEnabled(false);
					} catch (IOException ioe) {
						System.out.println("receive file wrong");
					}

					// filepathText.setText(filepath);
				}
			}
		});

		rejectfileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					DataOutputStream dos = new DataOutputStream(
							new BufferedOutputStream(socket.getOutputStream()));
					dos.writeUTF("no");
					dos.flush();
					dos.close();
					dis.close();// 别遗忘
					savefileButton.setEnabled(false);
					rejectfileButton.setEnabled(false);
				} catch (IOException ioe) {
					System.out.println("reject file wrong");
				}
			}
		});
		// chat pane
		chatTabItem.setLayout(new BoxLayout(chatTabItem, BoxLayout.Y_AXIS));

		final JTextArea chatReceiveArea = new JTextArea(chatContent);
		chatReceiveArea.setLineWrap(true);
		chatReceiveArea.setEditable(false);
		chatTabItem.add(new JScrollPane(chatReceiveArea));

		final JTextArea chatArea = new JTextArea();
		chatArea.setLineWrap(true);
		chatArea.setBackground(Color.white);
		chatTabItem.add(new JScrollPane(chatArea));

		JButton chatButton = new JButton("发送");
		if (messagetype.equals("chat")) {
			chatButton.setText("回复");
			tabbedPane.setSelectedIndex(1);
		}
		chatButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				chatContent = chatArea.getText();
				new ChatClient(IP, myname, myIP, chatContent).start();
			}
		});
		chatTabItem.add(chatButton);
		// message pane
		messageTabItem
				.setLayout(new BoxLayout(messageTabItem, BoxLayout.Y_AXIS));

		final JLabel idLabel = new JLabel();
		messageTabItem.add(idLabel);

		final JLabel nameLabel = new JLabel(myname);
		messageTabItem.add(nameLabel);

		time = new Date();
		final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
		final JLabel nowtimeLabel = new JLabel(df.format(time));
		messageTabItem.add(nowtimeLabel);

		JPanel bodyPane = new JPanel();
		bodyPane.setLayout(new BorderLayout());
		messageTabItem.add(bodyPane);

		JPanel leftPane = new JPanel();
		leftPane.setLayout(new BorderLayout());
		bodyPane.add(leftPane, BorderLayout.WEST);

		final JLabel subjectLabel = new JLabel("Subject");
		leftPane.add(subjectLabel, BorderLayout.NORTH);

		final JLabel contextLabel = new JLabel("Content");
		leftPane.add(contextLabel, BorderLayout.CENTER);

		final JLabel timeLabel = new JLabel("Time");
		leftPane.add(timeLabel, BorderLayout.SOUTH);

		JPanel rightPane = new JPanel();
		rightPane.setLayout(new BorderLayout());
		bodyPane.add(rightPane, BorderLayout.CENTER);

		final JTextField subjectField = new JTextField();
		rightPane.add(subjectField, BorderLayout.NORTH);

		final JTextArea contentArea = new JTextArea();
		contentArea.setLineWrap(true);
		contentArea.setBackground(Color.white);
		rightPane.add(new JScrollPane(contentArea), BorderLayout.CENTER);

		final JTextField timeField = new JTextField(df.format(time));// Formatted
		rightPane.add(timeField, BorderLayout.SOUTH);

		JPanel buttonPane = new JPanel();
		messageTabItem.add(buttonPane);
		// buttonPane.setLayout();

		JButton messageButton = new JButton("发送");
		messageButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				messageSubject = subjectField.getText();
				messageContent = contentArea.getText();
				try {
					df.applyPattern("yyyy-MM-dd  HH:mm:ss");
					messageTime = df.parse(timeField.getText());
				} catch (ParseException e1) {
					System.out.println(e1);
				}
				// messageTime=time;
				new XmlClient(IP, myname, myIP, messageSubject, messageContent,
						messageTime).start();
			}
		});
		buttonPane.add(messageButton);

		JButton messageSaveButton = new JButton("保存");
		messageSaveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AixzMessageProcessor xml = AixzMessageProcessor.getInstance();
				xml.openXML();
				messageSubject = subjectField.getText();
				messageContent = contentArea.getText();
				String date = null;
				try {
					df.applyPattern("yyyy-MM-dd  HH:mm:ss");
					messageTime = df.parse(timeField.getText());
					df.applyPattern("yyyyMMdd");
					date = df.format(messageTime);
					System.out.println(date);
				} catch (ParseException e1) {
					System.out.println(e1);
				}
				String id = idLabel.getText();
				if (!messagetype.equals("message")) {
					df.applyPattern("yyyyMMddHHmmss");
					id = df.format(messageTime);
				}
				String adder = nameLabel.getText();
				String addtime = nowtimeLabel.getText();
				xml.addMessage(date, id, adder, addtime, messageSubject,
						messageContent, timeField.getText());
				xml.saveXML();
			}
		});
		buttonPane.add(messageSaveButton);

		if (messagetype.equals("message")) {
			timeField.setText(df.format(messageTime));
			nowtimeLabel.setText(df.format(time));
			df.applyPattern("yyyyMMddHHmmss");
			idLabel.setText(df.format(messageTime));
			nameLabel.setText(username);
			subjectField.setText(messageSubject);
			contentArea.setText(messageContent);

		}
		frame.setVisible(true);
	}// showface

}
